import os
from flask import Flask
from flask_restful import Api
from flask_cors import CORS
from dotenv import load_dotenv
from models import db

# 加载环境变量
load_dotenv()

# 导入调度器
from scheduler import scheduler

def create_app():
    app = Flask(__name__)
    
    # 配置
    app.config['SECRET_KEY'] = os.getenv('SECRET_KEY', 'dev-secret-key')
    app.config['SQLALCHEMY_DATABASE_URI'] = f"mysql+pymysql://{os.getenv('DB_USER', 'root')}:{os.getenv('DB_PASSWORD', 'Gaa3252988..')}@{os.getenv('DB_HOST', 'localhost')}:{os.getenv('DB_PORT', '3306')}/{os.getenv('DB_NAME', 'wx_dinner')}"
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    app.config['DEBUG'] = os.getenv('DEBUG', 'True').lower() == 'true'
    
    # 初始化扩展
    db.init_app(app)
    CORS(app)
    
    # 初始化API
    api = Api(app)
    
    # 注册路由
    from routes import register_routes
    register_routes(api)
    
    # 注册错误处理器
    from errors import register_error_handlers
    register_error_handlers(app)
    
    # 启动定时任务调度器
    with app.app_context():
        scheduler.start()
    
    return app

if __name__ == '__main__':
    app = create_app()
    app.run(debug=True, host='0.0.0.0', port=5000)